<template>
  <div style="padding:30px;">
    <el-form ref="queryFrom" :inline="true" :model="queryFrom" class="demo-form-inline">
      <el-form-item>
        <el-button type="primary" class="el-button--mini" icon="el-icon-search" @click="queryData">查询</el-button>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" class="el-button--mini" icon="el-icon-plus" @click="onAddParnetMenu">新增类目</el-button>
      </el-form-item>
    </el-form>
    <el-divider />
    <el-table
      v-loading="loading"
      :data="tableData"
      style="width: 100%;margin-bottom: 20px;"
      row-key="id"
      border
      lazy
      :load="load"
      element-loading-text="拼命加载中"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}"
      :row-style="{height:'10px'}"
      :cell-style="{padding:'0px'}"
    >
      <el-table-column
        prop="id"
        label="ID"
        sortable
        width="180"
      />
      <el-table-column
        prop="name"
        label="类目名称"
        width="180"
      />
      <el-table-column
        prop="iconUrl"
        label="类目图标"
        width="170"
        align="center"
      >
        <template slot-scope="scope">

          <el-image
            style="width: 50px; height: 50px"
            :src="scope.row.iconUrl"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline" />
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        prop="picUrl"
        label="类目图片"
        width="170"
        align="center"
      >
        <template slot-scope="scope">

          <el-image
            style="width: 120px; height: 50px"
            :src="scope.row.picUrl"
          >
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline" />
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column
        prop="frontDesc"
        label="简介"
        width="180"
      />
      <el-table-column
        prop="keywords"
        label="关键字"
        width="170"
        align="center"
      >
        <template slot-scope="scope">
          <el-tag
            v-for="tag in scope.row.keywords.split(',')"
            :key="tag"
            :disable-transitions="true"
            style="margin-left: 10px;"
          >
            {{ tag || '' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="level" align="center" label="级别" width="150px">
        <template slot-scope="scope">
          <el-tag :type="scope.row.level | levelTagTypeFilter">
            {{ scope.row.level | levelTagFilter }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="isShow" align="center" label="是否上架" width="150px">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isShow | isShowTagTypeFilter">
            {{ scope.row.isShow | isShowTagFilter }}
          </el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="id" label="操作" align="center">
        <template slot-scope="scope">
          <div>
            <el-button size="small" class="el-button--mini" icon="el-icon-edit" @click="onEdit(scope.row)">编辑</el-button>
            <el-button v-if="scope.row.level=='L1'" class="el-button--mini" type="primary" size="small" icon="el-icon-plus" @click="onAdd(scope.row)">添加</el-button>
            <el-button :type="scope.row.isShow | isShowButTypeFilter" class="el-button--mini" size="small" icon="el-icon-close" @click="forbiddenCategory(scope.row)">{{ scope.row.isShow ==1 ?'下架':'上架' }}</el-button>
          </div>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog
      v-loading="dialogLoading"
      :title="dialogTitle"
      :visible.sync="dialogFormVisible"
      element-loading-text="拼命加载中"
      :close-on-click-modal="false"
      :before-close="closeDialog"
      :show-close="false"
    >
      <el-form
        ref="editForm"
        :model="editForm"
        :rules="rules"
      >
        <div v-if="!add">
          <el-form-item v-show="isAdd" label="上级类目" :label-width="formLabelWidth" prop="parnetName">
            <el-input
              v-model="parnetName"
              autocomplete="off"
              maxlength="20"
              :disabled="true"
              class="el-input--mini"
            />
          </el-form-item>
        </div>
        <el-form-item label="类目名称" :label-width="formLabelWidth" prop="name">
          <el-input
            v-model="editForm.name"
            autocomplete="off"
            maxlength="20"
            show-word-limit
            prefix-icon="el-icon-edit"
            class="el-input--mini"
          />
        </el-form-item>
        <el-form-item label="关键字" :label-width="formLabelWidth" prop="keywords">
          <el-tag
            v-for="tag in keywords"
            :key="tag"
            closable
            :disable-transitions="false"
            style="margin-left: 10px;"
            @close="handleClose(tag)"
          >
            {{ tag }}
          </el-tag>
          <el-input
            v-if="inputVisible"
            ref="saveTagInput"
            v-model="inputValue"
            class="input-new-tag"
            size="small"
            @keyup.enter.native="handleInputConfirm"
            @blur="handleInputConfirm"
          />
          <el-button type="primary" class="el-input--medium" size="small" style="margin-left: 10px;" @click="showInput">增加</el-button>
        </el-form-item>

        <el-form-item label="是否上架" :label-width="formLabelWidth" prop="editIsShow">
          <el-select v-model="editForm.isShow" placeholder="请选择" class="el-input--mini">
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value"
              class="el-select--mini"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="类目icon" :label-width="formLabelWidth" prop="iconUrl">

          <el-upload
            class="avatar-uploader"
            :action="doUpload"
            :headers="{ token: token }"
            :show-file-list="false"
            :auto-upload="true"
            list-type="picture-card"
            accept="image/jpeg,image/gif,image/png,image/bmp"
            :on-success="onSuccess"
          >
            <label class="el-upload-list__item-status-label">
              <i class="el-icon-upload-success el-icon-check" />
            </label>
            <img v-if="editForm.iconUrl" :src="editForm.iconUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>

        </el-form-item>
        <el-form-item label="类目图片" :label-width="formLabelWidth" prop="imgUrl">

          <el-upload
            class="avatar-uploader"
            :action="doUpload"
            :headers="{ token: token }"
            :show-file-list="false"
            :auto-upload="true"
            list-type="picture-card"
            accept="image/jpeg,image/gif,image/png,image/bmp"
            :on-success="onSuccessImgUrl"
          >
            <label class="el-upload-list__item-status-label">
              <i class="el-icon-upload-success el-icon-check" />
            </label>
            <img v-if="editForm.imgUrl" :src="editForm.imgUrl" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon" />
          </el-upload>

        </el-form-item>

        <el-form-item label="类目简介" :label-width="formLabelWidth" prop="frontDesc">
          <el-input
            v-model="editForm.frontDesc"
            autocomplete="off"
            maxlength="200"
            show-word-limit
            prefix-icon="el-icon-paperclip"
            class="el-input--mini"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button class="el-button--mini" @click="cancelChange('editForm')">取 消</el-button>
        <el-button class="el-button--mini" type="primary" @click="updateShopCategory('editForm')">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { queryShopCategoryList, updateShopCategory, addShopCategory } from '@/api/shop/shopcategory'
import { mapGetters } from 'vuex'
export default {
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    },
    timefilters(val) {
      if (val == null || val === '') {
        return '暂无时间'
      } else {
        const d = new Date(val) // val 为表格内取到的后台时间
        const month =
          d.getMonth() + 1 < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1
        const day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate()
        const hours = d.getHours() < 10 ? '0' + d.getHours() : d.getHours()
        const min = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes()
        const sec = d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds()
        const times = d.getFullYear() + '-' + month + '-' + day + ' ' + hours + ':' + min + ':' + sec
        return times
      }
    },
    statusfilters(val) {
      if (val == null || val === '') {
        return '--'
      } else {
        if (val === 1) {
          return '正常'
        }
        if (val === 9) {
          return '禁用'
        }
        if (val === 3) {
          return '删除'
        }
        if (val === 4) {
          return '非法'
        }
      }
    },
    statusTagFilter(val) {
      const statusMap = {
        'L1': 'success',
        'L2': 'info',
        '3': 'danger',
        '4': 'danger'
      }
      return statusMap[val]
    },
    levelTagFilter(val) {
      const statusMap = {
        'L1': '一级类目',
        'L2': '二级类目'
      }
      return statusMap[val]
    },
    levelTagTypeFilter(val) {
      const statusMap = {
        'L1': '',
        'L2': 'info'
      }
      return statusMap[val]
    },
    isShowTagFilter(val) {
      const statusMap = {
        '1': '已上架',
        '0': '已下架'
      }
      return statusMap[val]
    },
    isShowTagTypeFilter(val) {
      const statusMap = {
        '1': '',
        '0': 'info'
      }
      return statusMap[val]
    },
    isShowButTypeFilter(val) {
      const statusMap = {
        '1': 'info',
        '0': 'danger'
      }
      return statusMap[val]
    },
    editStatusTagFilter(val) {
      const statusMap = {
        '1': 'warning',
        '9': 'success'
      }
      return statusMap[val]
    }
  },
  data() {
    return {
      doUpload: process.env.VUE_APP_BASE_API + '/qiniuConfig/upload',
      dialogFormVisible: false,
      dialogLoading: true,
      dialogTitle: '',
      formLabelWidth: '100px',
      options: [{
        value: 1,
        label: '上架'
      }, {
        value: 0,
        label: '下架'
      }],
      queryFrom: {
        name: ''
      },
      rules: {
        name: [{ required: true, message: '请填写类目名称', trigger: 'blur' }],
        // keywords: [{ required: true, message: '请填写类目关键字', trigger: 'blur' }],
        // editIsShow: [{ required: true, message: '类目是否上架' }],
        iconUrl: [{ required: true, message: '请填写类目图标', trigger: 'blur' }],
        imgUrl: [{ required: true, message: '请填写类目展示图标', trigger: 'blur' }],
        frontDesc: [{ required: true, message: '请填写类目简介', trigger: 'blur' }]
      },
      tableData: [],
      editForm: {
        id: '',
        name: '',
        iconUrl: '',
        frontName: '',
        keywords: '',
        frontDesc: '',
        parentId: '',
        imgUrl: '',
        isShow: '',
        level: ''

      },
      isAdd: false,
      parnetName: '',
      parnetId: '',
      add: false,
      loading: true,
      dialogImageUrl: '',
      dialogVisible: false,
      fileIcon: null,
      inputVisible: false,
      inputValue: '',
      keywords: []

    }
  },
  computed: {
    ...mapGetters(['fileUpload', 'token'])
  },
  created() {
    this.queryData()
  },
  methods: {
    queryData() {
      this.clear()
      this.loading = true
      var qq = Object.assign(this.queryFrom)
      queryShopCategoryList(qq).then(response => {
        const menus = response.data
        menus.forEach((p) => {
          this.tableData.push({
            id: p.id,
            name: p.name,
            frontDesc: p.frontDesc,
            frontName: p.frontName,
            iconUrl: p.iconUrl,
            children: p.children,
            hasChildren: true,
            keywords: p.keywords,
            level: p.level,
            parentId: p.parentId,
            picUrl: p.picUrl,
            isShow: p.isShow

          })
        })
        this.loading = false
      })
    },
    load(tree, treeNode, resolve) {
      console.log(tree)
      const tr = []
      tree.children.forEach((p) => {
        if (p.children !== null && p.children.length > 0) {
          tr.push({
            id: p.id,
            name: p.name,
            frontDesc: p.frontDesc,
            frontName: p.frontName,
            iconUrl: p.iconUrl,
            children: p.children,
            keywords: p.keywords,
            level: p.level,
            parentId: p.parentId,
            picUrl: p.picUrl,
            hasChildren: false,
            isShow: p.isShow
          })
        } else {
          tr.push({
            id: p.id,
            name: p.name,
            frontDesc: p.frontDesc,
            frontName: p.frontName,
            iconUrl: p.iconUrl,
            children: p.children,
            keywords: p.keywords,
            level: p.level,
            parentId: p.parentId,
            picUrl: p.picUrl,
            hasChildren: false,
            isShow: p.isShow
          })
        }
      })
      resolve(tr)
    },
    onEdit(row) {
      this.isAdd = false
      this.dialogFormVisible = true
      this.dialogLoading = false
      this.dialogTitle = '编辑类目'
      this.editForm.name = row.name
      this.editForm.id = row.id
      this.editForm.iconUrl = row.iconUrl
      this.editForm.frontName = row.formName
      this.editForm.keywords = row.keywords
      this.editForm.frontDesc = row.frontDesc
      this.editForm.parentId = row.parentId
      this.editForm.imgUrl = row.picUrl
      this.editForm.isShow = row.isShow
      this.dialogImageUrl = row.iconUrl
      this.keywords = []
      this.keywords = row.keywords.split(',')
    },
    onAdd(row) {
      this.isAdd = true
      this.parnetName = row.name
      this.parnetId = row.id
      this.dialogFormVisible = true
      this.dialogLoading = false
      this.dialogTitle = '添加类目'
      this.editForm.parentId = row.id
      this.editForm.level = 'L2'
      this.editForm.name = ''
      this.editForm.status = ''
      this.editForm.code = ''
      this.editForm.url = ''
      this.editForm.icon = ''
      this.keywords = []
    },
    onAddParnetMenu() {
      this.isAdd = true
      this.add = true
      this.dialogFormVisible = true
      this.dialogLoading = false
      this.dialogTitle = '添加类目'
      this.editForm.id = ''
      this.editForm.name = ''
      this.editForm.status = ''
      this.editForm.code = ''
      this.editForm.url = ''
      this.editForm.icon = ''
      this.editForm.parentId = 0
      this.editForm.level = 'L1'
    },
    forbiddenCategory(row) {
      const title = row.isShow === 1 ? '下架' : '上架'
      this.$confirm('确认要' + title + '该类目: ' + row.name + ' 吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        updateShopCategory({ id: row.id, isShow: row.isShow === 1 ? 0 : 1 }).then(response => {
          this.$notify({ title: response.msg, duration: 1000, type: 'success' })
          this.clear()
          this.queryData()
        })
      }).catch(() => {
      })
    },
    updateShopCategory(formName) {
      this.$refs[formName].validate((valida) => {
        if (valida) {
          if (!this.isAdd) {
            this.editForm.keywords = this.keywords.join(',')
            updateShopCategory(this.editForm).then(response => {
              this.$notify({ title: response.msg, duration: 1000, type: 'success' })
              this.dialogFormVisible = false
              this.clear()
              this.queryData()
            })
          } else {
            this.editForm.keywords = this.keywords.join(',')
            addShopCategory(this.editForm).then(response => {
              this.$notify({ title: response.msg, duration: 1000, type: 'success' })
              this.clear()
              this.queryData()
            })
          }
        } else {
          return false
        }
        this.$refs[formName].clearValidate()
      })
    },
    onReset(formName) {
      this.$refs[formName].resetFields()
    }, handleSizeChange(val) {
      this.page.pageSize = val
      this.queryData()
    },
    handleCurrentChange(val) {
      this.page.currentPage = val
      this.queryData()
    },
    clear() {
      this.dialogFormVisible = false
      this.tableData = []
      this.editForm.id = null
      this.editForm.name = null
      this.add = false
      this.parnetId = null

      this.editForm.iconUrl = null
      this.editForm.frontName = null
      this.editForm.keywords = null
      this.editForm.frontDesc = null
      this.editForm.parentId = null
      this.editForm.imgUrl = null
      this.editForm.isShow = null
      this.editForm.level = null
      this.keywords = []
    },
    cancelChange(formName) {
      this.dialogFormVisible = false
      this.$refs[formName].clearValidate()
      this.editForm.id = null
      this.editForm.name = null
      this.add = false
      this.parnetId = ''
      this.editForm.id = null
      this.editForm.name = null
      this.editForm.iconUrl = null
      this.editForm.frontName = null
      this.editForm.keywords = null
      this.editForm.frontDesc = null
      this.editForm.parentId = null
      this.editForm.imgUrl = null
      this.editForm.isShow = null
      this.editForm.level = null
      this.dialogImageUrl = null
      this.keywords = []
    },
    closeDialog() {
      this.clear()
      this.cancelChange()
    },
    handlePictureCardPreview(file) {
      this.editForm.iconUrl = file.url
      this.dialogVisible = true
    },
    handleDownload(file) {
    },
    onSuccess(file) {
      this.$message.success(file.msg)
      this.editForm.iconUrl = file.data
    },
    onSuccessImgUrl(file) {
      this.$message.success(file.msg)
      this.editForm.imgUrl = file.data
    },
    uploadError(file) {

    },
    handleClose(tag) {
      this.keywords.splice(this.keywords.indexOf(tag), 1)
    },

    showInput() {
      this.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },

    handleInputConfirm() {
      const inputValue = this.inputValue
      if (inputValue) {
        this.keywords.push(inputValue)
      }
      this.inputVisible = false
      this.inputValue = ''
    }
  }
}
</script>

<style scoped>
.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 148px;
    height: 148px;
    line-height: 148px;
    text-align: center;
  }
  .avatar {
    width: 148px;
    height: 148px;
    display: block;
  }
  .el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
